package com.john.bluetoothtest2;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.john.bluetoothtest2.User_Info.DBOpenHelper;

import java.util.Locale;


public class HomeActivity extends AppCompatActivity implements View.OnClickListener {


    private long firstTime=0;

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch(keyCode){
            case KeyEvent.KEYCODE_BACK://点击返回键
                long secondTime = System.currentTimeMillis();//以毫秒为单位
                if(secondTime -firstTime>2000){
                    Toast.makeText(this, "再按一次返回退出程序", Toast.LENGTH_SHORT).show();
                    firstTime=secondTime;
                }else{
                    finish();
                    System.exit(0);
                }
                return true;
        }
        return super.onKeyUp(keyCode, event);
    }










    //实例化TextToSpeech类
    private TextToSpeech textToSpeech;
    private Context mContext;
    private Button button;
    private static int PERMISSION_GRANTED = 0;
    private String[] permissions = new String[]{Manifest.permission.INTERNET, Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.SYSTEM_ALERT_WINDOW,
            Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};


    private DBOpenHelper dbOpenHelper;
    private final int REQUEST_ENABLE_BT = 0xa01;
    private final int PERMISSION_REQUEST_COARSE_LOCATION = 0xb01;
    private Dialog mDialog;
    private String TAG = "debug";
    private EditText username;
    private FloatingActionButton add;
    private ArrayAdapter<String> mAdapter;
    private RadioGroup gender_selector;
    private RadioButton boys, girl;
    private EditText userschool;
    private EditText userClass_information;
    private EditText userbluetooth_address;
    private RadioButton Turn_on_bluetooth;
    private RadioButton Turn_off_bluetooth;
    private RadioButton scan_device;
    private TextView show_bluetooth_name;
    private Button Add_to;
    private BluetoothAdapter mBluetoothAdapter;
    public Context context;


    // 广播接收发现蓝牙设备
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @SuppressLint("MissingPermission")
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                Log.d(TAG, "开始扫描...");
            }

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device != null) {
                    // 添加到ListView的Adapter。
                    mAdapter.add("设备名:" + device.getName() + "\n设备地址:" + device.getAddress());
                    mAdapter.notifyDataSetChanged();
                    // Log.d(device.getName(),device.getAddress());
                    String text = device.getAddress();
                    Log.d("", "" + text);

                    inserData1(dbOpenHelper.getReadableDatabase(), text);
                    Toast.makeText(HomeActivity.this, "打卡成功", Toast.LENGTH_SHORT).show();

                    textToSpeech.setPitch(1.0f); // 在系统设置里也可以修改音调
                    textToSpeech.speak("打卡成功", TextToSpeech.QUEUE_FLUSH, null);

                }
            }

            if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                Log.d(TAG, "扫描结束.");
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);


        all();
    }

    private void all() {
        getPermission();

        tts();


        dbOpenHelper = new DBOpenHelper(HomeActivity.this, "db_dict", null, 1);//实例化dbOpenHelper对象，用来创建数据库


        blue();
        findViewById(R.id.init).setOnClickListener(this);
        findViewById(R.id.discovery).setOnClickListener(this);

        add = findViewById(R.id.add);
        add.setOnClickListener(this);
    }

    private void blue() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
            }
        }


        // 注册广播接收器。
        // 接收蓝牙发现
        IntentFilter filterFound = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filterFound);
        IntentFilter filterStart = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        registerReceiver(mReceiver, filterStart);
        IntentFilter filterFinish = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver, filterFinish);


        mAdapter = new ArrayAdapter<>(HomeActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1);

        ListView list = findViewById(R.id.listView);
        list.setAdapter(mAdapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            }
        });
    }

    private void tts() {
        mContext = HomeActivity.this;
        TextToSpeech.OnInitListener onInitListener = new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    int result = textToSpeech.setLanguage(Locale.CHINA);
                    if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                        Toast.makeText(HomeActivity.this, "LANG_MISSING_DATA  or LANG_NOT_SUPPORTED !", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        };
        textToSpeech = new TextToSpeech(this, onInitListener);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.init:
                init();
                break;

            case R.id.discovery:
                discovery();
                break;
            case R.id.add:
                btn_add();
                break;
            default:
                break;
        }
    }

    // 初始化蓝牙设备
    @SuppressLint("MissingPermission")
    private void init() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // 检查设备是否支持蓝牙设备
        if (mBluetoothAdapter == null) {
            Log.d(TAG, "设备不支持蓝牙");

            // 不支持蓝牙，退出。
            return;
        }

        // 如果用户的设备没有开启蓝牙，则弹出开启蓝牙设备的对话框，让用户开启蓝牙
        if (!mBluetoothAdapter.isEnabled()) {
            Log.d(TAG, "请求用户打开蓝牙");

            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            // 接下去，在onActivityResult回调判断
        } else {
            Toast.makeText(HomeActivity.this, "蓝牙打开成功", Toast.LENGTH_SHORT).show();
        }
    }

    // 启动蓝牙发现...
    @SuppressLint("MissingPermission")
    private void discovery() {
        if (mBluetoothAdapter == null) {
            init();
        }

        mBluetoothAdapter.startDiscovery();
    }

    // 可选方法，非必需
    // 此方法使自身的蓝牙设备可以被其他蓝牙设备扫描到，
    // 注意时间阈值。0 - 3600 秒。
    // 通常设置时间为120秒。
    @SuppressLint("MissingPermission")
    private void enable_discovery() {
        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);

        // 第二个参数可设置的范围是0~3600秒，在此时间区间（窗口期）内可被发现
        // 任何不在此区间的值都将被自动设置成120秒。
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3600);

        startActivity(discoverableIntent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == RESULT_OK) {
                Log.d(TAG, "打开蓝牙成功！");
            }

            if (resultCode == RESULT_CANCELED) {
                Log.d(TAG, "放弃打开蓝牙！");
            }

        } else {
            Log.d(TAG, "蓝牙异常！");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);

        //关闭数据库
                if (dbOpenHelper != null) {
                    dbOpenHelper.close();
                }
            }


    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_COARSE_LOCATION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                }

                break;
        }
    }


    private void btn_add() {


        /***
         * 弹窗显示
         */
        Dialog dialogs = new Dialog(this);
        LayoutInflater inflaterdialog = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
        View view = inflaterdialog.inflate(R.layout.activity_add, null);

        username = view.findViewById(R.id.name);
        gender_selector = view.findViewById(R.id.gender_selector);
        gender_selector.setOnCheckedChangeListener(mChangeRadio);
        boys = view.findViewById(R.id.boys);
        girl = view.findViewById(R.id.girl);
        userClass_information = view.findViewById(R.id.Class_information);
        userbluetooth_address = view.findViewById(R.id.bluetooth_address);


        Add_to = view.findViewById(R.id.Add_to);
        Add_to.setOnClickListener(this);
        dialogs.setContentView(view);
        Add_to.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String name = username.getText().toString();//名字
//                if (TextUtils.isEmpty(name)){
//                    Toast.makeText(HomeActivity.this, "名字不为空", Toast.LENGTH_SHORT).show();
//                }
                String gender = String.valueOf(boys.getText());//性别
                String student_class = userClass_information.getText().toString();//班级
//                if (TextUtils.isEmpty(student_class )){
//                    Toast.makeText(HomeActivity.this, "班级不为空", Toast.LENGTH_SHORT).show();
//                }
                String bluetooth_address = userbluetooth_address.getText().toString();//蓝牙地址
//                if (TextUtils.isEmpty(student_class )){
//                    Toast.makeText(HomeActivity.this, "蓝牙地址不为空", Toast.LENGTH_SHORT).show();
//                }




                Log.d(TAG, "" + name);
                Log.d(TAG, "" + gender);
                Log.d(TAG, "" + student_class);
                Log.d(TAG, "" + bluetooth_address);

                inserData(dbOpenHelper.getReadableDatabase(), name, gender, student_class, bluetooth_address);
                Toast.makeText(HomeActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                textToSpeech.speak("添加成功", TextToSpeech.QUEUE_FLUSH, null);
                dialogs.cancel();
                dialogs.dismiss();


            }
        });


        dialogs.show();


    }

    private RadioGroup.OnCheckedChangeListener mChangeRadio = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == boys.getId()) {
                // Log.d(TAG,""+boys.getText());

            } else if (checkedId == girl.getId()) {
                // Log.d(TAG,""+girl.getText());
            }
        }
    };


    //插入数据
    private void inserData(SQLiteDatabase sqLiteDatabase, String name, String gender, String student_class, String bluetooth_address) {

        ContentValues values = new ContentValues();
        values.put("name", name);
        values.put("gender", gender);
        values.put("student_class", student_class);
        values.put("bluetooth_address", bluetooth_address);
        sqLiteDatabase.insert("tb_dict", null, values);
    }


    //插入数据
    private void inserData1(SQLiteDatabase sqLiteDatabase, String bluetooth_address) {

        ContentValues values = new ContentValues();
        values.put("bluetooth_address", bluetooth_address);
        sqLiteDatabase.insert("tb_dict", null, values);
    }


    /**
     * 动态获取权限
     */


    private void getPermission() {
        //判断是否有权限
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //请求权限
            ActivityCompat.requestPermissions(this, permissions, PERMISSION_GRANTED);
            //判断是否需要 向用户解释，为什么要申请该权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_CONTACTS)) {
                Toast.makeText(this, "shouldShowRequestPermissionRationale", Toast.LENGTH_SHORT).show();
            }
        }
    }


}
